import mongoose from "mongoose";

const ratingSchema = new mongoose.Schema(
  {
    userId: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "User",
      required: true,
    },
    torrentId: {
      type: String,
      required: true,
    },
    score: {
      type: Number,
      required: true,
      min: 1,
      max: 5,
    },
    comment: {
      type: String,
      default: "",
    },
    // 存储详细的评分维度数据
    dimensions: {
      technical: {
        successDownload: { type: Boolean, default: true }, // 该用户下载是否成功
        downloadSpeed: { type: Number }, // 下载速度 (KB/s)
      },
      community: {
        responseTime: { type: Number }, // 响应时间 (小时)
        helpfulness: { type: Number, min: 1, max: 5 }, // 帮助程度
      },
    },
    createdAt: {
      type: Date,
      default: Date.now,
    },
    updatedAt: {
      type: Date,
      default: Date.now,
    },
  },
  {
    timestamps: true,
  }
);

// 创建复合索引确保每个用户对每个种子只能有一个评分
ratingSchema.index({ userId: 1, torrentId: 1 }, { unique: true });

// 更新时间钩子
ratingSchema.pre("findOneAndUpdate", function () {
  this.set({ updatedAt: Date.now() });
});

// 评分状态更新钩子
ratingSchema.post("save", async function () {
  try {
    // 可以在这里添加逻辑来更新种子的评分摘要统计
    // 这会在每次新评分或评分更新时触发
  } catch (error) {
    console.error("Error updating torrent rating stats:", error);
  }
});

export default mongoose.model("Rating", ratingSchema);
